<?php

namespace App\Services;
use Illuminate\Support\Facades\Log;
use OSS\Core\OssException;
use OSS\OssClient;

class OssService
{
    public $ossClient;

    public function __construct()
    {
        $accessId = env('ALIYUNCS_ACCESS_KEY_ID', '');
        $accessKey = env('ALIYUNCS_ACCESS_KEY_SECRET', '');
        $endPoint = env('ALIYUNCS_END_POINT', '');
        $this->ossClient = new OssClient($accessId, $accessKey, $endPoint);
    }

    private static $_instance = NULL;


    public static function getInstance()
    {
        if (is_null(self::$_instance)) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

    /**
     *  oss上传图片
     * @param $OssFile
     * @param $localFile
     * @return bool
     * @throws \OSS\Core\OssException
     */
    public  function uploadFile($OssFile, $localFile)
    {
        try {
            $result = $this->ossClient->uploadFile(env('ALIYUNCS_PITUITARY_BUCKET', 'zz-med-stg-pri'), $OssFile, $localFile);
            if ($result['oss-redirects'] == 0) {
                @unlink($localFile);
                return $result['oss-request-url'];
            } else {
                Log::error('阿里OSS上传错误异常返回：' . json_encode($result));
                return false;
            }
        } catch (OssException $e) {
            Log::error('上传异常失败 : ' . $localFile . $e->getMessage());
            return false;
        }
    }
    
 
   /**
     *   获取图片url(通用)
     * @param $arr
     * @return array
     */
    public  function getPicUrl($ret)
    {
         $bucket = env('ALIYUNCS_PITUITARY_BUCKET','zz-med-stg-pri');
         $img = [];
         try {
            $timeout = 1800; //  设置URL过期时长，默认60
            if (!empty($ret)) {
                foreach ($ret as $v) {
                  
                    //之前公钥上传的
                    if($v->date == "0000-00-00"){
                        $tempFile = $v->file;
                    }else{
                        $tempFile = $this->ossClient->signUrl($bucket,'pituitary_file/'.$v->date."/".$v->filename,$timeout);
                    } 
                      
                     $img[] = [
                         "id" => $v->id,
                         "file" => $tempFile
                     ];
                }
            } 
        } catch (\Exception $exception) {
            return [];
        }
            return $img;
    }

}